﻿using Brilliant_see.App.Services;
using Brilliant_see.Core.AbstractClass;
using Brilliant_see.Core.Models;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System.Collections.ObjectModel;

namespace Brilliant_see.App.ViewModels
{
    public partial class SearchViewModel : ObservableObject
    {
        private readonly SearchService _searchService;

        /// <summary>
        /// 图源列表
        /// </summary>
        public List<MapSourceSelectItemModel> MapSources => _searchService.MapSources;

        /// <summary>
        /// 搜索结果
        /// </summary>
        public ObservableCollection<Comic> SearchResults { get; set; } = new();

        private bool _isShowSearchView;

        /// <summary>
        /// 是否显示搜索视图
        /// </summary>
        public bool IsShowSearchView
        {
            get => _isShowSearchView;
            set
            {
                if (SetProperty(ref _isShowSearchView, value))
                {
                    if (value)
                    {
                        SearchResults.CollectionChanged += SearchResults_CollectionChanged;
                    }
                    else
                    {
                        SearchResults.CollectionChanged -= SearchResults_CollectionChanged;
                    }
                }
            }
        }

        public SearchViewModel(SearchService searchService)
        {
            _searchService = searchService;
        }

        /// <summary>
        /// 监听搜索结果集合变化则隐藏搜索视图
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SearchResults_CollectionChanged(object? sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
            {
                IsShowSearchView = false;
            }
        }

        /// <summary>
        /// 从所有选中图源中搜索关键字
        /// </summary>
        /// <param name="keyWord"></param>
        /// <returns></returns>
        [RelayCommand]
        private async Task SearchAsync(string keyWord)
        {
            IsShowSearchView = true;
            await _searchService.SearchAsync(SearchResults, keyWord);
        }
    }
}